package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Sonic
 * @version : 1.0
 * @createTime : 2024-12-05  19:58
 * @description :
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;


    /**
     * @param: [ordersSubmitDTO]
     * @return: com.sky.vo.OrderSubmitVO
     * @description: 提交订单, 涉及到多表插入、删除操作，需要添加事务标签
     **/
    @Override
    @Transactional // 方法执行完才会提交事务，也就是最后才会真执行这些
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 异常订单处理, 抛出异常
        // 地址簿address_book为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // TODO 地址校验
        // 检查用户的收货地址是否超过配送范围
//        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 购物车shopping_cart为空或查询到的条目数量为0
        ShoppingCart shoppingCart = new ShoppingCart();
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 订单表orders插入一条
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis())); // 用时间戳作为订单号
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setUserId(currentId);
        orderMapper.insert(orders);
        // 订单明细表order_detail插入n条, 从shoppingCart表查询并拷贝
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空购物车shopping_cart数据
        shoppingCartMapper.clean(currentId);
        // 封装返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return 返回值为第 8步的支付参数
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成 预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 通过WebSocket向管理端发送消息
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "Order id is " + orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * @param: [ordersPageQueryDTO]
     * @return: com.sky.result.PageResult
     * @description: 历史订单分页查询
     **/
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 先分页查询order的数据
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> result = page.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        // page.getResult的结果是order的列表,根据此列表中的orderId查询order_details
        // 在循环中构造VO对象
        // 如果查询结果不为null才进行下面这步
//        for (Orders orders : result) { // 关于page的遍历是这样的？
        for (Orders orders : page) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @param: [id]
     * @return: com.sky.vo.OrderVO
     * @description: 通过OrderId查询订单信息以及orderDetail信息
     **/
    @Override
    public OrderVO getByOrderId(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * @param: [id]
     * @return: void
     * @description: 用户取消订单, 分布不同阶段进行处理
     **/
    @Override
    public void cancelOrder(Long id) throws Exception {
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // 查询订单状态
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer status = orders.getStatus();
        // 待支付和待接单可以直接取消订单
        if (status < Orders.CONFIRMED) {
            orders.setStatus(Orders.CANCELLED);
            if (status == Orders.TO_BE_CONFIRMED) {
                // 待接单需要退款
                //     * @param outTradeNo    商户订单号
                //     * @param outRefundNo   商户退款单号
                //     * @param refund        退款金额
                //     * @param total         原订单金额
                weChatPayUtil.refund(orders.getNumber(),
                        orders.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01));
                orders.setPayStatus(Orders.REFUND);
            }
        }
        // 已接单和派送中需要沟通商家取消
        if (status == 3 || status == 4) {
            // 直接抛异常？
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 取消订单后需要update订单状态为已取消
        orders.setCancelReason("User cancel order.");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * @param: [id]
     * @return: void
     * @description: 再来一单，将订单商品再次添加到购物车
     **/
    @Override
    public void repetition(Long id) {
        // 查询OrderDetail
//        Orders orders = orderMapper.getByOrderId(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 重新 insert 到 shoppingCart 表
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        Long currentId = BaseContext.getCurrentId();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(currentId);
//            shoppingCartMapper.insert(shoppingCart);
            shoppingCartList.add(shoppingCart);
        }
        // 尽量用批量插入, 不要每次创建都插入
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * @param: [ordersPageQueryDTO]
     * @return: com.sky.result.PageResult
     * @description: 条件、分页 查询订单
     **/
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 先分页查询orders
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        // 构造orderVO对象
        List<OrderVO> orderVOList = new ArrayList<>();
        // 遍历page,构建添加属性orderDishes
        for (Orders orders : page.getResult()) {
            // 查询order_detail表
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            // 合成orderDishes字符串
            List<String> orderDishesList = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                orderDishesList.add(orderDetail.getName() + "*" + orderDetail.getNumber() + "; ");
            }
            String orderDishes = String.join("", orderDishesList);
            // 构建OrderVO并添加到列表orderVOList
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDishes(orderDishes);
            orderVOList.add(orderVO);
        }

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @param: []
     * @return: com.sky.vo.OrderStatisticsVO
     * @description: 统计 2\3\4 状态的订单的数量
     **/
    @Override
    public OrderStatisticsVO statistics() {
        // * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // //待接单数量
        // private Integer toBeConfirmed;
        // //待派送数量
        // private Integer confirmed;
        // //派送中数量
        // private Integer deliveryInProgress;
        List<Statistics> statisticsList = orderDetailMapper.statistics();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        for (Statistics statistics : statisticsList) {
            switch (statistics.getStatus()) {
                case 2:
                    orderStatisticsVO.setToBeConfirmed(statistics.getCount());
                    break;
                case 3:
                    orderStatisticsVO.setConfirmed(statistics.getCount());
                    break;
                case 4:
                    orderStatisticsVO.setDeliveryInProgress(statistics.getCount());
                    break;
            }
        }
        return orderStatisticsVO;
    }

    /**
     * @param: [ordersConfirmDTO]
     * @return: void
     * @description: 更新订单状态为已接单
     **/
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * @param: [ordersRejectionDTO]
     * @return: void
     * @description: 商家 拒绝 订单
     **/
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 查询订单数据, 判断是否为待接单状态
        Orders orders = orderMapper.getByOrderId(ordersRejectionDTO.getId());
        if (orders != null && orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态\拒绝理由\取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        // 判断是否进行了支付, 若支付需要退款
        if (orders.getPayStatus() == Orders.PAID) {
            //支付状态 0未支付 1已支付 2退款
            orders.setPayStatus(Orders.REFUND);
            weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
        }
        Orders newOrder = Orders.builder()
                .id(orders.getId())
                .rejectionReason(orders.getRejectionReason())
                .cancelTime(orders.getCancelTime())
                .status(orders.getStatus())
                .payStatus(orders.getPayStatus())
                .build();
        orderMapper.update(newOrder);
    }

    /**
     * @param: [ordersCancelDTO]
     * @return: void
     * @description: 商家 取消 订单
     **/
    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders orders = orderMapper.getByOrderId(ordersCancelDTO.getId());
        // 查询支付状态, 已支付需要退款
        if (orders.getPayStatus() == Orders.PAID) {
            weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
        }
        // 创建修改对象
        // 修改订单状态为已取消、支付状态为已退款
        // 指定取消原因、时间
        Orders newOrders = Orders.builder()
                .id(orders.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(newOrders);
    }

    /**
     * @param: [id]
     * @return: void
     * @description: 派送订单
     **/
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null || orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders newOrder = Orders.builder()
                .id(orders.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(newOrder);
    }

    /**
     * @param: [id]
     * @return: void
     * @description: 完成订单
     **/
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders newOrder = Orders.builder()
                .id(orders.getId())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(newOrder);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    // TODO 还没有配置好，还在等待审核；感觉可以抽取成一个工具类
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * @param: [id]
     * @return: void
     * @description: 客户催单
     **/
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 通过WebSocket向管理端发送消息
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "Order id is " + orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
